package com.sharecar.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import com.android.sharecar.model.UserTalkMsg;
import com.sharecar.db.DB;

public class UserTalkMsgService {
	private static UserTalkMsgService service;

	private UserTalkMsgService() {
	}

	public static UserTalkMsgService getInstance() {
		if (null == service) {
			service = new UserTalkMsgService();
		}
		return service;
	}

	public void addTalk(UserTalkMsg talkMsg) {
		Connection conn = DB.getConn();
		try {
			conn.setAutoCommit(false);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		String sql = "insert into UserTalks values (null, ?, ?, ?, ?)";
		PreparedStatement pstmt = DB.prepare(conn, sql);
		try {
			pstmt.setString(1, talkMsg.getContent());
			pstmt.setInt(2, talkMsg.getCommentNum());
			pstmt.setTimestamp(3,
					new Timestamp(talkMsg.getPostTime().getTime()));
			pstmt.setInt(4, talkMsg.getUser().getUserId());

			pstmt.executeUpdate();
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				conn.setAutoCommit(true);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			DB.close(pstmt);
			DB.close(conn);
		}
	}
}
